from contextlib import asynccontextmanager

import uvicorn
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from starlette.responses import PlainTextResponse
from tortoise.contrib.fastapi import register_tortoise

from app.middleware.auth_middleware import AuthMiddleware
from app.models.account_models import Account
from app.routers import api
from app.settings.load_config import load_config
from app.settings.tortoise_settings import TORTOISE_CONFIG

app = FastAPI(
    version="1.0.0",
    title="ITplanet-weather",

)
settings = load_config()

app.include_router(api)
app.add_middleware(AuthMiddleware)


@app.on_event("startup")
async def startup_event():
    register_tortoise(app=app, config=TORTOISE_CONFIG, generate_schemas=True)
    await Account.create(
        firstName="admin",
        lastName="admin",
        email="admin@main.com",
        password="pass"

    )


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return PlainTextResponse(str(exc), status_code=400)


if __name__ == "__main__":
    uvicorn.run(
        app=app,
        host=settings.server.host,
        port=settings.server.port,
    )
